package admin

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"html/template"
	"os"
	"strconv"
	"time"
	"xianzhi/models"
	"xianzhi/service"
	"xianzhi/utils"
)

type SchoolController struct {
	BaseController
}

func (c *SchoolController) Add() {
	p := map[string]interface{}{}
	p["relation"] = false
	p["level"] = 1
	_, provinceList := service.GetRegionList(p)
	c.Data["provinceList"] = provinceList
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/school/add.html"
}

func (c *SchoolController) DoAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()
	provinceId, _ := strconv.Atoi(input["province_id"][0])
	if provinceId <= 0 {
		res = utils.ResJson(0, "请选择省", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	cityId, _ := strconv.Atoi(input["city_id"][0])
	if cityId <= 0 {
		res = utils.ResJson(0, "请选择市", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["name"][0]) <= 0 {
		res = utils.ResJson(0, "请输入名称", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["introduce"][0]) <= 0 {
		res = utils.ResJson(0, "请输入介绍", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	/*if len(input["bai_ke_url"][0]) <= 0 {
		res = utils.ResJson(0, "请输入百科链接", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["public_space_url"][0]) <= 0 {
		res = utils.ResJson(0, "请输入公共空间链接", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}*/
	_, err := service.AddSchool(input)
	if err != nil {
		res = utils.ResJson(0, "添加失败", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res = utils.ResJson(1, "添加成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *SchoolController) ExcelAdd() {
	p := map[string]interface{}{}
	p["relation"] = false
	p["level"] = 1
	_, provinceList := service.GetRegionList(p)
	c.Data["provinceList"] = provinceList
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/school/excel_add.html"
}

func (c *SchoolController) DoExcelAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()
	provinceId, _ := strconv.Atoi(input["province_id"][0])
	if provinceId <= 0 {
		res = utils.ResJson(0, "请选择省", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	cityId, _ := strconv.Atoi(input["city_id"][0])
	if cityId <= 0 {
		res = utils.ResJson(0, "请选择市", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["excel_file_path"][0]) <= 0 {
		res = utils.ResJson(0, "请上传excel文件", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	_, err := service.AddSchoolFromExcel(input)
	if err != nil {
		res = utils.ResJson(0, "添加失败", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res = utils.ResJson(1, "添加成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *SchoolController) Edit() {
	id := utils.Atoi64(c.Ctx.Input.Param(":id"))
	p := map[string]interface{}{}
	p["relation"] = true
	p["id"] = id
	record := service.GetSchoolInfo(p)
	c.Data["record"] = record
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	p = map[string]interface{}{}
	p["relation"] = false
	p["level"] = 1
	_, provinceList := service.GetRegionList(p)
	c.Data["provinceList"] = provinceList
	if record.City.Id > 0 {
		p = map[string]interface{}{}
		p["relation"] = false
		p["level"] = 2
		p["parent_id"] = record.Province.Id
		_, cityList := service.GetRegionList(p)
		c.Data["cityList"] = cityList
	}
	c.TplName = "admin/school/edit.html"
}

func (c *SchoolController) DoEdit() {
	var res *utils.ResJsonStruct
	input := c.Input()
	provinceId, _ := strconv.Atoi(input["province_id"][0])
	if provinceId <= 0 {
		res = utils.ResJson(0, "请选择省", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	cityId, _ := strconv.Atoi(input["city_id"][0])
	if cityId <= 0 {
		res = utils.ResJson(0, "请选择市", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["name"][0]) <= 0 {
		res = utils.ResJson(0, "请输入名称", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["introduce"][0]) <= 0 {
		res = utils.ResJson(0, "请输入介绍", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	/*if len(input["bai_ke_url"][0]) <= 0 {
		res = utils.ResJson(0, "请输入百科链接", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["public_space_url"][0]) <= 0 {
		res = utils.ResJson(0, "请输入公共空间链接", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}*/
	_, err := service.EditSchool(input)
	if err != nil {
		res = utils.ResJson(0, "修改失败", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res = utils.ResJson(1, "修改成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *SchoolController) ShowList() {
	curPage, _ := strconv.Atoi(c.GetString("p"))
	if curPage <= 0 {
		curPage = 1
	}

	perCount, _ := beego.AppConfig.Int("percount")
	symPageCount, _ := beego.AppConfig.Int("symmetricpagecount")

	p := map[string]interface{}{}
	provinceId := c.GetString("province_id")
	c.Data["provinceId"] = utils.Atoi64(provinceId)
	if len(provinceId) > 0 {
		p["provinceId"] = provinceId
	}
	cityId := c.GetString("city_id")
	c.Data["cityId"] = utils.Atoi64(cityId)
	if len(cityId) > 0 {
		p["cityId"] = cityId
	}
	name := c.GetString("name")
	c.Data["name"] = name
	if len(name) > 0 {
		p["name"] = name
	}
	isExcellent := c.GetString("is_excellent")
	if len(isExcellent) > 0 {
		p["isExcellent"] = isExcellent
		c.Data["isExcellent"], _ = strconv.Atoi(isExcellent)
	} else {
		c.Data["isExcellent"] = -1
	}
	isAssist := c.GetString("is_assist")
	if len(isAssist) > 0 {
		p["isAssist"] = isAssist
		c.Data["isAssist"], _ = strconv.Atoi(isAssist)
	} else {
		c.Data["isAssist"] = -1
	}

	exportExcel := c.GetString("export_excel")
	if len(exportExcel) <= 0 {
		p["curPage"] = curPage
		p["perCount"] = perCount
	}

	p["relation"] = true
	p["convert"] = true
	totalCount, recordList := service.GetSchoolList(p)

	if len(exportExcel) > 0 && totalCount > 0 {
		c.ExportExcel(recordList)
		return
	}

	paginator := utils.NewPaginator(int(totalCount), perCount, symPageCount, curPage)
	c.Data["paginator"] = paginator.GetPageHtml()

	c.Data["recordList"] = recordList
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())

	p = map[string]interface{}{}
	p["relation"] = false
	p["level"] = 1
	_, provinceList := service.GetRegionList(p)
	c.Data["provinceList"] = provinceList

	if len(provinceId) > 0 {
		p = map[string]interface{}{}
		p["relation"] = false
		p["level"] = 2
		p["parent_id"] = provinceId
		_, cityList := service.GetRegionList(p)
		c.Data["cityList"] = cityList
	}

	c.TplName = "admin/school/list.html"
}

func (c *SchoolController) ExportExcel(recordList []*models.School) {
	f := excelize.NewFile()
	sheetName := "sheet1"
	index := f.NewSheet(sheetName)
	col := 65
	header := []string{"学校名称", "学校介绍", "所在城市", "状态"}
	for _, h := range header {
		f.SetCellValue(sheetName, string(col) + "1", h)
		col++
	}
	row := 2
	titleStyle, _ := f.NewStyle(`{"alignment":{"horizontal":"center"},"font":{"bold":true}}`)
	style, _ := f.NewStyle(`{"alignment":{"horizontal":"center"}}`)
	f.SetColWidth(sheetName, "A", "B", 50)
	f.SetColWidth(sheetName, "C", "D", 20)
	f.SetCellStyle(sheetName, "A1", fmt.Sprintf("D%d", len(recordList) + 1), style)
	f.SetCellStyle(sheetName, "A1", "D1", titleStyle)
	for _, record := range recordList {
		f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), record.Name)
		f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), record.Introduce)
		f.SetCellValue(sheetName, fmt.Sprintf("C%d", row), record.City.Name)
		f.SetCellValue(sheetName, fmt.Sprintf("D%d", row), record.StatusShow)
		row++
	}
	f.SetActiveSheet(index)
	d := "./static/export/" + time.Now().Format("20060102") + "/"
	if _, err := os.Stat(d); err != nil {
		os.MkdirAll(d, os.ModePerm)
	}
	saveName := d + "学校_" + time.Now().Format("20060102150405") + ".xlsx"
	err := f.SaveAs(saveName)
	if err != nil {
		c.Ctx.WriteString("导出失败")
		return
	}
	c.Ctx.Output.Download(saveName)
}